package lesson6.example2;

import java.lang.management.ManagementFactory;
import java.util.Random;
import java.util.concurrent.ExecutorService;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;

import com.sun.jdmk.comm.HtmlAdaptorServer;

public class Test {
    private static Random random = new Random();
    public static void main(String[] args) throws Exception {
        ExecutorService es1 = ThreadPoolMonitor.newCachedThreadPool("test-pool-1");
        ThreadPoolParam threadPoolParam1 = new ThreadPoolParam(es1);
 
        ExecutorService es2 = ThreadPoolMonitor.newCachedThreadPool("test-pool-2");
        ThreadPoolParam threadPoolParam2 = new ThreadPoolParam(es2);
 
		MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
		ObjectName a1 = new ObjectName("test-pool-1:type=threadPoolParam");
		mbs.registerMBean(threadPoolParam1, a1);

		ObjectName a2 = new ObjectName("test-pool-2:type=threadPoolParam");
		mbs.registerMBean(threadPoolParam2, a2);

		ObjectName adapterName = new ObjectName("test-pool:name=htmladapter,port=8082");
		HtmlAdaptorServer adapter = new HtmlAdaptorServer();
		adapter.start();
		mbs.registerMBean(adapter, adapterName);
 
        executeTask(es1);
        executeTask(es2);
        Thread.sleep(1000 * 60 * 60);
    }
 
    private static void executeTask(ExecutorService es) {
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                int temp = i;
                es.submit(() -> {
                    try {
                        Thread.sleep(random.nextInt(60) * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(temp);
                });
            }
        }).start();
    }
}
